package com.project_test.kun.travelling_1st.Discovery;


import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;

import com.android.volley.Cache;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.project_test.kun.travelling_1st.MainActivity;
import com.project_test.kun.travelling_1st.R;
import com.project_test.kun.travelling_1st.Utils.CustomVolley;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */


public class Discovery_Fragment extends Fragment {
    private int page = 1;
    private RequestQueue mRequestQueue;
    private String detail_path_1="http://www.handybest.com/index.php?m=Api&c=Topics&a=topic_info&id=";
    private String detail_path_2="&device_token=864394010925172&push_token=363646a50016412a414f89bae67b47cd972d5bd5&mobile_type=Android&mobile_model=GT-N7100%2C4.4.2&version_code=10000";
    private String path_1 = "http://www.handybest.com/index.php?m=Api&c=index&a=getTopicList&page=";
    private String path_2 = "&device_token=864394010925172&push_token=363646a50016412a414f89bae67b47cd972d5bd5&mobile_type=Android&mobile_model=GT-N7100%2C4.4.2&version_code=10000";
    private JSONObject originalJson;
    private PullToRefreshListView discover_total_list;
    private List<discover_bean> mDiscover_beans = new ArrayList<>();
    private Discover_Adapter mAdapter;
    private ConnectivityManager mCwjManager;


    Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
            originalJson = (JSONObject) msg.obj;
            parseJson(originalJson);
            mAdapter.notifyDataSetChanged();
            if (discover_total_list.isRefreshing()) {
                discover_total_list.onRefreshComplete();
            }}
            if (msg.what==2){
                discover_total_list.onRefreshComplete();

            }
        }

    };


    public Discovery_Fragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        String path = path_1 + page + path_2;
        mAdapter = new Discover_Adapter();
        jsonRequest(path);
    }

    private void parseJson(JSONObject jsonObject) {
        try {
            JSONArray jsonArray = jsonObject.optJSONArray("data");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                discover_bean item = new discover_bean();
                item.parseJson(json);
                mDiscover_beans.add(item);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void jsonRequest(final String path) {
        mRequestQueue = CustomVolley.getInstance(getContext()).sRequestQueue;
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(JsonObjectRequest.Method.GET,
                path, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Message msg = new Message();
                msg.what=1;
                msg.obj = response;
                hander.sendMessage(msg);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //            获取缓存
                Cache cache = mRequestQueue.getCache();
                if (cache != null) {
                    Cache.Entry entry = cache.get(path);
                    if (entry != null) {
                        byte[] data = entry.data;
                        if (data != null) {
                            try {
                                String result = new String(data, "UTF-8");
                                JSONObject obj = new JSONObject(result);
                                Message msg = new Message();
                                msg.obj = obj;
                                hander.sendMessage(msg);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
        mRequestQueue.add(jsonObjectRequest);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View ret = inflater.inflate(R.layout.fragment_discovery_, container, false);
        discover_total_list = (PullToRefreshListView) ret.findViewById(R.id.discover_fragment_total_list);
        discover_total_list.setAdapter(mAdapter);
        discover_total_list.setMode(PullToRefreshBase.Mode.BOTH);
        discover_total_list.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override//下拉刷新
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                mCwjManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = mCwjManager.getActiveNetworkInfo();
                if (info == null || !mCwjManager.getBackgroundDataSetting()){
                    hander.sendEmptyMessageDelayed(2,500);
                }else{
                    mDiscover_beans.clear();
                    page = 0;
                    String path = path_1 + page + path_2;
                    jsonRequest(path);
                }
            }

            @Override//上拉加载更多
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                String path = path_1 + page + path_2;
                jsonRequest(path);
            }
        });
        discover_total_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String itemId=mDiscover_beans.get(position-1).getId();
                String detailPath=detail_path_1+itemId+detail_path_2;
                Intent intent=new Intent(getActivity(),Discover_Detail_Activity.class);
                intent.putExtra("detailPath",detailPath);

                startActivity(intent);
            }
        });
        return ret;

    }

    class Discover_Adapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mDiscover_beans == null ? 0 : mDiscover_beans.size();
        }

        @Override
        public Object getItem(int position) {
            return mDiscover_beans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View ret = view;
            LayoutInflater inflater = LayoutInflater.from(getContext());
            ret = inflater.inflate(R.layout.discover_item, viewGroup, false);
            Holder holder = (Holder) ret.getTag();
            if (holder == null) {
                holder = new Holder(ret);
                ret.setTag(holder);
            }
            holder.bindView(i, mDiscover_beans.get(i));
            return ret;
        }

        private class Holder {
            private ImageView discover_fragment_item_img;

            public Holder(View itemView) {
                discover_fragment_item_img = (ImageView) itemView.findViewById(R.id.discover_fragment_item_img);
            }

            public void bindView(int i, discover_bean item) {
                String path = item.getHead_pic();
                if (path != null) {
                    Picasso.with(getContext()).load(path).into(discover_fragment_item_img);
                }
            }
        }
    }
}
